<?php
// +----------------------------------------------------------------------
// | Description: 商城接口
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\mini\controller;

use think\facade\Db;
use app\Request;
use think\Env;

class ApiShop
{


    //根据门店查询订单信息
    public function getShopOrderList(Request $request)
    {
        $param = $request->param();
        if (!$param['shop_id'])
        {
            return app('json')->fail('参数有误');
            
        }
        //查询
        $url = env('SHOP.shop_url').'/api/crm/order_list?' . http_build_query($param);
        $apiResponse = $this->callApi($url);
        // var_dump($apiResponse);die;
        if ($apiResponse)
        {
            $data = json_decode($apiResponse, true);
        }else
        {
            $data = [];
        }
        
        if(!empty($data))
        {
            foreach($data['data']['data'] as $key => $val)
            {
                $data['data']['data'][$key]['goods'] = [];
                foreach ($val['cart_id'] as $cartId)
                {
                    if (isset($val['_info'][$cartId]['cart_info']['productInfo']))
                    {
                         $data['data']['data'][$key]['goods'] = $val['_info'][$cartId]['cart_info']['productInfo'];
                    }
                }
                unset($data['data']['data'][$key]['_info']);
            }
        }
        return json(['data'=>$data,'code'=>1]);
    }


    // 门店核销订单
    public function updateStoreOrder(Request $request)
    {
        $param = $request->param();
        if (!$param['order_id'])
        {
            return app('json')->fail('参数有误');
            
        }
        //查询
        $url = env('SHOP.shop_url').'/api/crm/update_order?order_id=' . $param['order_id'];
        $apiResponse = $this->callApi($url);
        if ($apiResponse)
        {
            $data = json_decode($apiResponse, true);
            if($data['status'] != 200)
            {
                return json(['msg'=>$data['msg'],'code'=>0]);
            }
        }else
        {
            $data = [];
        }
        return json(['data'=>$data,'code'=>1]);
        
    }


















    private function callApi($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'cURL Error: '. curl_error($curl);
            return false;
        }
        curl_close($curl);
        return $response;
    }


}